package cn.git.socket;

import cn.git.mapper.ProductMapper;
import cn.git.socket.handler.SocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description: socket接口入口信息
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-09-27
 */
@Slf4j
@Component
public class CustomSocketServer {

    @Autowired
    private ProductMapper productMapper;

    /**
     * 初始化启动socket服务,监听7777端口
     *
     * @throws IOException
     */
    @PostConstruct
    public void socketServerInit() throws IOException {
        new Thread(() -> {
            try {
                // 监听7777端口
                log.info("开始启动socket服务信息，端口监听 7777");
                ServerSocket serverSocket = new ServerSocket(7777);

                // 循环监听
                while (true) {
                    log.info("等待客户端连接...");
                    Socket clientSocket = serverSocket.accept();
                    ThreadPoolUtil.THREAD_POOL.execute(
                        // 构建handler
                        SocketHandler.builder().clientSocket(clientSocket).productMapper(productMapper).build()
                    );
                    log.info("客户端连接成功，当前连接数：{}", ThreadPoolUtil.THREAD_POOL.getActiveCount());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}
